package com.academysmart.bookagolf.provider;

import com.academysmart.bookagolf.config.ApplicationConfigValues;
import com.academysmart.bookagolf.model.Field;
import com.academysmart.bookagolf.model.GameBatch;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by valer_000 on 4/9/14.
 */
public enum GameBatchesProvider {

    INSTANCE;

    private List<GameBatch> gameBatches;

    private GameBatchesProvider() {
        refreshGameBatches();
    }

    public void refreshGameBatches() {
        gameBatches = new ArrayList<>();
        try {
            List<Field> fieldList = FieldProvider.INSTANCE.getFields();
            for (Field field : fieldList) {
                List<GameBatch> batchesOnField = GolfApiProvider.getGolfApi()
                        .getGamesBatches(ApplicationConfigValues.CLUB_ID, field.getId());
                if (batchesOnField != null && !batchesOnField.isEmpty()) {
                    gameBatches.addAll(batchesOnField);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void saveGameBatch(GameBatch batch) {
        if (batch == null) {
            return;
        }
        if (!GolfApiProvider.getGolfApi().saveGameBatch(ApplicationConfigValues.CLUB_ID
                , batch.getGolfFieldId(), batch)) {
            //TODO: save game batch to local storage
            System.out.println("failed to save game batch");
        }
        gameBatches.add(batch);
    }

    public void updateGameBatch(GameBatch batch) {
        if (batch == null) {
            return;
        }
        if (!GolfApiProvider.getGolfApi().updateGameBatch(ApplicationConfigValues.CLUB_ID
                , batch.getGolfFieldId(), batch)) {
            //TODO: save game batch to local storage
            System.out.println("failed to update game batch");
        }
    }

    public GameBatch getGameBatchById(int id) {
        for (GameBatch batch : gameBatches) {
            if (batch.getId() == id) {
                return batch;
            }
        }
        return null;
    }

    public boolean deleteGameBatch(int id) {
        GameBatch batch = getGameBatchById(id);
        if (batch != null) {
            return GolfApiProvider.getGolfApi().deleteGameBatch(ApplicationConfigValues.CLUB_ID, batch.getGolfFieldId() ,id);
        }
        return  false;
    }

    public List<GameBatch> getGames() {
        return gameBatches;
    }
}
